#include "log.h"
#include <stdlib.h>
#include <string.h>


log_level curr_log_level = INFO;
FILE * log_file = NULL;

static const char * level_names[] = {
    "DEBUG",
    "INFO",
    "WARNING",
    "ERROR",
    "FATAL"
};

static char timestamp[20] = {0};  // 时间戳缓冲区

void log_init(const char * filename){
    if(log_file != NULL) return;
    log_file = fopen(filename,"a");
    if(!log_file){
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    setvbuf(log_file, NULL, _IONBF, 0);  // 缓冲区立即刷新
}

void log_close(){
    if(log_file){
        fclose(log_file);
        log_file = NULL;
    }
}

void set_level(log_level level){
    curr_log_level = level;
}

void log_write(log_level level, const char * format, ...){
    if(level < curr_log_level){
        return;
    }

    time_t now = time(NULL);
    struct tm * tm_now = localtime(&now);
    strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", tm_now);
    va_list args;
    va_start(args, format);
    fprintf(log_file, "[%s] [%s]", timestamp, level_names[level]);
    vfprintf(log_file, format, args);
    fprintf(log_file, "\n");
    fflush(log_file);
    va_end(args);
    if(level == FATAL){
        log_close();
        exit(EXIT_FAILURE);
    }
}

#if 0
int main(int argc, char * argv[]){
    log_init("../data/log.txt");
    set_level(WARNING);
    LOG_INFO("Application started");
    LOG_DEBUG("Debug message - this won't appear if default level is INFO");
    LOG_WARNING("Something might be wrong");
    
    for (int i = 0; i < 10; i++) {
        LOG_INFO("Progress: %d%%", i * 10);
    }
    
    LOG_ERROR("%s","Failed to connect to server");
    LOG_FATAL("Critical error - shutting down");
    return 0;
}
#endif